import Dialog from "./index.vue";
import { createApp, h, ref, isVNode } from "vue";
import i18n from "@/lang";
import router from "@/router";
import { FullScreen, Close } from "@element-plus/icons-vue"; // 图标
import config from "@/configs/globalConfig";
import ElementPlus from "element-plus";
import locale from "element-plus/dist/locale/zh-cn";
export default function openDialog(props = {}, slots = {}) {
  const isOpen = ref(true);
  const container = document.createElement("div");
  props = typeof props === "object" ? props : { title: props };
  slots = isVNode(slots) ? { default: slots } : slots;
  const app = createApp({
    setup() {
      return () =>
        h(
          Dialog,
          {
            modelValue: isOpen.value,
            "onUpdate:modelValue": (value) => {
              isOpen.value = value;
            },
            onClosed: () => {
              app.unmount();
              document.body.removeChild(container);
            },
            ...props,
          },
          // 转换插槽函数为 VNode
          Object.entries(slots).reduce((acc, [name, slot]) => {
            acc[name] = typeof slot === "function" ? slot : () => slot;
            return acc;
          }, {})
        );
    },
  });
  app.component("FullScreen", FullScreen);
  app.component("Close", Close);
  app
    .use(router)
    .use(i18n)
    .use(ElementPlus, {
      locale: config.lang === "zh" ? locale : null,
      size: config.elementPlus.size,
    });
  app.mount(container);
  document.body.appendChild(container);

  return {
    close: () => {
      isOpen.value = false;
    },
  };
}
